package com.xique.park.service.command.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.constant.HttpStatus;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.utils.command.CommandResultUtil;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.api.IParkGarageCommandApi;
import com.xique.park.bean.domain.ParkGarage;
import com.xique.park.constant.CommandConstant;
import com.xique.park.constant.ParkApiName;
import com.xique.park.service.command.service.IParkGarageCommandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * 车库命令 service
 *
 * @author: xique
 */
@Service
public class ParkGarageCommandServiceImpl extends CommandCommServiceImpl implements IParkGarageCommandService {

    @Autowired
    private IParkGarageCommandApi parkGarageCommandApi;

    @Override
    public AjaxResult downSingleDevParkGarage(String sn, ParkGarage parkGarage) {
        JSONObject dtObj = new JSONObject(1);
        JSONArray garagesArr = new JSONArray(1);
        JSONObject garageObj = new JSONObject();
        garageObj.put(CommandConstant.GARAGE_ID, parkGarage.getId());
        garageObj.put(CommandConstant.PARENT_GARAGE_ID, null != parkGarage.getPid() ? parkGarage.getPid() : 0);
        garageObj.put(CommandConstant.SPACE_CNT, parkGarage.getTotalSpace());
        garageObj.put(CommandConstant.ADJUST_SPACE_CNT, parkGarage.getTempEmptySpace());
        garagesArr.add(garageObj);
        dtObj.put(CommandConstant.GARAGES, garagesArr);

        JSONObject obj = getBaseObj(SecurityUtils.getParkId(), sn, ParkApiName.COMMAND_SET_GARAGE_PARAM, ParkApiName.VER_2_0);
        obj.put(CommandConstant.DATA, dtObj);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = parkGarageCommandApi.downParkGarage(params);
        return CommandResultUtil.handleCommandResult(commandResult, "");
    }

    @Override
    public AjaxResult downSingleDevParkGarageList(Long parkId, String sn, List<ParkGarage> list) {
        JSONObject dtObj = new JSONObject(1);
        JSONArray garagesArr = new JSONArray(list.size());
        for (ParkGarage parkGarage : list) {
            JSONObject garageObj = new JSONObject();
            garageObj.put(CommandConstant.GARAGE_ID, parkGarage.getId());
            garageObj.put(CommandConstant.PARENT_GARAGE_ID, null != parkGarage.getPid() ? parkGarage.getPid() : 0);
            garageObj.put(CommandConstant.SPACE_CNT, parkGarage.getTotalSpace());
            garageObj.put(CommandConstant.ADJUST_SPACE_CNT, parkGarage.getTempEmptySpace());
            garagesArr.add(garageObj);
        }
        dtObj.put(CommandConstant.GARAGES, garagesArr);

        JSONObject obj = getBaseObj(parkId, sn, ParkApiName.COMMAND_SET_GARAGE_PARAM, ParkApiName.VER_2_0);
        obj.put(CommandConstant.DATA, dtObj);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = parkGarageCommandApi.downParkGarage(params);
        return CommandResultUtil.handleCommandResult(commandResult, "");
    }

    @Override
    public AjaxResult downParkGarage(ParkGarage parkGarage, String reminderMsg) {
        Long parkId = SecurityUtils.getParkId();
        if (null != parkId) {
            List<String> devCodes = getMainDeviceCodesByParkId(parkId);
            if (CollectionUtil.isNotEmpty(devCodes)) {
                boolean commandResult = true;
                StringBuilder errMsg = new StringBuilder();
                for (String devCode : devCodes) {
                    if (StringUtils.isNotEmpty(devCode)) {
                        AjaxResult result = downSingleDevParkGarage(devCode, parkGarage);
                        if (result.get(AjaxResult.CODE_TAG).equals(HttpStatus.ERROR)) {
                            commandResult = false;
                            errMsg.append(result.get(AjaxResult.MSG_TAG)).append("，");
                        }
                    }
                }
                if (commandResult) {
                    return AjaxResult.success(reminderMsg + "下发成功");
                } else {
                    return AjaxResult.commandError(reminderMsg + "下发失败，请重新下发，错误原因：" + errMsg);
                }
            } else {
                return AjaxResult.success(reminderMsg + "车场没有添加主相机，无需下发");
            }
        } else {
            return AjaxResult.commandError(reminderMsg + "下发失败，车场参数不能为空");
        }
    }

    @Override
    public AjaxResult delSingleDevParkGarage(String sn, Long garageId) {
        JSONObject dtObj = new JSONObject(1);
        JSONArray garagesArr = new JSONArray(1);
        JSONObject garageObj = new JSONObject();
        garageObj.put(CommandConstant.GARAGE_ID, garageId);
        garagesArr.add(garageObj);
        dtObj.put(CommandConstant.GARAGES, garagesArr);
        // 0表示删除指定车库，1表示删除所有车库
        dtObj.put("del_all", 0);

        JSONObject obj = getBaseObj(SecurityUtils.getParkId(), sn, ParkApiName.COMMAND_DEL_GARAGE_PARAM, ParkApiName.VER_2_0);
        obj.put(CommandConstant.DATA, dtObj);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = parkGarageCommandApi.delParkGarage(params);
        return CommandResultUtil.handleCommandResult(commandResult, "");
    }

    @Override
    public AjaxResult delParkGarage(Long garageId, String reminderMsg) {
        Long parkId = SecurityUtils.getParkId();
        if (null != parkId) {
            List<String> devCodes = getMainDeviceCodesByParkId(parkId);
            if (!CollectionUtils.isEmpty(devCodes)) {
                boolean commandResult = true;
                StringBuilder errMsg = new StringBuilder();
                for (String devCode : devCodes) {
                    if (StringUtils.isNotEmpty(devCode)) {
                        AjaxResult result = delSingleDevParkGarage(devCode, garageId);
                        if (result.get(AjaxResult.CODE_TAG).equals(HttpStatus.ERROR)) {
                            commandResult = false;
                            errMsg.append(result.get(AjaxResult.MSG_TAG)).append("，");
                        }
                    }
                }
                if (commandResult) {
                    return AjaxResult.success(reminderMsg + "下发成功");
                } else {
                    return AjaxResult.commandError(reminderMsg + "下发失败，请重新下发，错误原因：" + errMsg);
                }
            } else {
                return AjaxResult.success(reminderMsg + "车场没有添加主相机，无需下发");
            }
        } else {
            return AjaxResult.commandError(reminderMsg + "下发失败，车场参数不能为空");
        }
    }

    /**
     * 更新车位相关信息
     */
    @Override
    public AjaxResult updateSpaces(Long parkId, Long garageId) {
        JSONObject dtObj = new JSONObject();
        dtObj.put("parkId", parkId);
        dtObj.put("garageId", garageId);

        JSONObject obj = getBaseObj(parkId, "", ParkApiName.COMMAND_UPDATE_SPACES, ParkApiName.VER_1_0);
        obj.put(CommandConstant.DATA, dtObj);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = parkGarageCommandApi.updateSpaces(params);
        return CommandResultUtil.handleCommandResult(commandResult, "");
    }

}
